package com.imay.live.activity.authentication;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.live.R;
import com.imay.live.activity.AboutIMayActivity;
import com.imay.live.activity.BaseRequestActivity;
import com.imay.live.activity.ProfileActivity;
import com.imay.live.activity.WebViewActivity;
import com.imay.live.helper.DialogFragmentHelper;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.LevelHelper;
import com.imay.live.helper.UrlHelper;
import com.imay.live.model.UserInfoModel;
import com.imay.live.model.UserModel;
import com.imay.live.model.WithdrawInfoModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.Result;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.GlideUtil;
import com.imay.live.utils.ToastUtil;

import static com.imay.live.proto.ResultCode.CodeSuccess;

/**
 * Created by lzx on 2017/04/20 0020.
 * 用户签约
 */

public class UserSignActivity extends BaseRequestActivity implements View.OnClickListener {
    LinearLayout linearLayout;
    public static final String TYPE = "type";
    static final String PAYTYPE = "paytype";
    static final String BROKEY = "broker";
    static final String TIP = "tip";
    public static final int RESULT = 0x110;
    int type = 0; //0 业余主播 1专业主播
    int paytype = 0; //0  未确认  2 已确认
    UserModel userModel;
    CheckBox sign_chekc;
    ImageView iv_vip;
    ImageView iv_comhead;
    RelativeLayout top_tips;
    TextView other;
    NameView nameView;
    String tip;

    /**
     * 默认推荐经纪人uid后面通过接口获取  暂时可用固定值 uid=27728   用   /v2/user/info   获取其信息
     *
     * @param type
     * @param paytype
     * @param userModel
     */
    public static void startActivityResult(Activity activity, int type, int paytype, String tip, UserModel userModel) {
        Intent starter = new Intent(activity, UserSignActivity.class);
        starter.putExtra(TYPE, type);
        starter.putExtra(PAYTYPE, paytype);
        starter.putExtra(BROKEY, userModel);
        starter.putExtra(TIP, tip);
        activity.startActivityForResult(starter, RESULT);
    }

    public static void startActivity(Context context) {
        Intent starter = new Intent(context, UserSignActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.usersign_layout;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        setTitle(getString(R.string.setting_balance_way));
        type = getIntent().getIntExtra(TYPE, -1);
        paytype = getIntent().getIntExtra(PAYTYPE, 0);
        userModel = getIntent().getParcelableExtra(BROKEY);
        tip = getIntent().getStringExtra(TIP);
        linearLayout = $(R.id.src_linear);
        top_tips = $(R.id.top_tips);

        sign_chekc = $(R.id.sign_chekc);
        iv_comhead = $(R.id.iv_comhead);
        iv_vip = $(R.id.iv_vip);
        if (type < 0) {
            LoadData();
        } else {
            fromData();
        }
    }

    private void LoadData() {
        ProtoRequestHelper.task(ProtoHttpFactory.getwithdrawInfo()).setTag(this.hashCode()).request(new ProtoCallBack() {
            @Override
            public void onRequestSuccess(String command, String data) {
                Result<WithdrawInfoModel> result = JSON.parseObject(data, new TypeReference<Result<WithdrawInfoModel>>() {
                }.getType());
                if (result.result == CodeSuccess && result.data != null) {
                    type = result.data.getIsSigned();
                    paytype = result.data.getSignConfirmStatus();
                    userModel = result.data.getBroker();
                    tip = result.data.getTip();
                    fromData();
                } else {
                    ToastUtil.show(UserSignActivity.this, getResources().getString(R.string.str_loaderror));
                }

            }

            @Override
            public void onRequestError(String command, int code, String message) {
                ToastUtil.show(UserSignActivity.this, getResources().getString(R.string.str_loaderror));
            }
        });
    }

    void fromData() {
        if (type == 0) {
            if (paytype == 0) {
                // 请求默认经纪
                ProtoRequestHelper.task(ProtoHttpFactory.getUserInfo(27728)).setTag(this.hashCode()).request(new ProtoCallBack() {
                    @Override
                    public void onRequestSuccess(String command, String data) {
                        Result<UserInfoModel> result = JSON.parseObject(data, new TypeReference<Result<UserInfoModel>>() {
                        }.getType());
                        if (result.result == CodeSuccess && result.data != null) {
                            UserModel userModel = result.data.getUser();
                            if (userModel != null) {
                                initView(userModel);
                            }

                        }
                    }

                    @Override
                    public void onRequestError(String command, int code, String message) {

                    }
                });
            } else {
                initView(userModel);
            }
        } else {//专业主播
            initView(userModel);
        }

    }

    private void initView(UserModel userModel) {
        if (userModel == null) {
            linearLayout.setVisibility(View.GONE);
            return;
        }
        linearLayout.setVisibility(View.VISIBLE);
        TextView tv_sign_status = $(R.id.tv_sign_status);
        if (nameView == null) {
            nameView = new NameView(this);
            linearLayout.addView(nameView, 1);
        }

        TextView tv_comtitle = $(R.id.tv_comtitle);
        TextView tv_meilino = $(R.id.tv_meilino);
        LinearLayout ll_check = $(R.id.ll_check);
        TextView tv_sign_des = $(R.id.tv_sign_des);
        TextView tv_live_level = $(R.id.tv_live_level);
        TextView tv_user_level = $(R.id.tv_user_level);
        TextView tv_signtip = $(R.id.tv_signtip);
        TextView sin_tip = $(R.id.sin_tip);
        TextView sign_ok = $(R.id.sign_ok);
        TextView sign_cancle = $(R.id.sign_cancle);
        sign_cancle.setOnClickListener(this);
        if (other == null) {
            other = otherTips();
            LinearLayout.LayoutParams otherparams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            otherparams.topMargin = (int) getResources().getDimension(R.dimen.sign_top);
            otherparams.bottomMargin = (int) getResources().getDimension(R.dimen.sign_top);
            linearLayout.addView(other, otherparams);
        }
        if (!TextUtils.isEmpty(tip)) {
            sin_tip.setText("*" + tip);
        }

        TextView tv_signments = $(R.id.tv_signments);
        tv_signments.setOnClickListener(this);
        String othertips = getResources().getString(R.string.sign_agreement);
        tv_signments.setTextColor(getResources().getColor(R.color.text_75));
        SpannableString spanstring = new SpannableString(othertips);
        int start = othertips.indexOf(" ") + 1;
        int end = othertips.lastIndexOf(" ");
        if (end > start) {
            spanstring.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.text_url)), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        }
        tv_signments.setText(spanstring);

        RelativeLayout sign_user = $(R.id.sign_user_);
        sign_user.setOnClickListener(this);
        sign_user.setTag(userModel.getUid());

        if (type == 0) {
            tv_sign_des.setText((getResources().getString(R.string.sign_toptips)));
            tv_sign_status.setText((getResources().getString(R.string.sign_timebalance)));
            if (paytype == 0) {
                sign_ok.setOnClickListener(this);
                sign_chekc.setVisibility(View.VISIBLE);
                nameView.setTextString(getResources().getString(R.string.sign_com));
                top_tips.setVisibility(View.VISIBLE);
                tv_signtip.setText(getResources().getString(R.string.sign_tips));
            } else {
                LinearLayout.LayoutParams mcheckparams = (LinearLayout.LayoutParams) ll_check.getLayoutParams();
                mcheckparams.topMargin = (int) getResources().getDimension(R.dimen.sign_pacetop);
                sign_ok.setBackground(getResources().getDrawable(R.drawable.shape_corner100_b2));
                sign_ok.setText(getResources().getString(R.string.sign_aleadyOK));
                sign_chekc.setVisibility(View.GONE);
                sign_cancle.setVisibility(View.GONE);
                nameView.setTextString(getResources().getString(R.string.sign_yourcom));
                top_tips.setVisibility(View.GONE);
            }
        } else {
            ll_check.setVisibility(View.INVISIBLE);
            tv_sign_status.setText((getResources().getString(R.string.sign_monbalance)));
            nameView.setTextString(getResources().getString(R.string.sign_info));
            if (paytype == 0) {
                sign_ok.setOnClickListener(this);
                sign_chekc.setVisibility(View.VISIBLE);
                tv_sign_des.setText((getResources().getString(R.string.sign_isokmode)));
                top_tips.setVisibility(View.VISIBLE);
                tv_signtip.setText(getResources().getString(R.string.issigntips, userModel.getNick()));
            } else {
                LinearLayout.LayoutParams mcheckparams = (LinearLayout.LayoutParams) ll_check.getLayoutParams();
                mcheckparams.topMargin = (int) getResources().getDimension(R.dimen.sign_pacetop);
                sign_ok.setBackground(getResources().getDrawable(R.drawable.shape_corner100_b2));
                sign_ok.setText(getResources().getString(R.string.sign_aleadyOK));
                sign_chekc.setVisibility(View.GONE);
                sign_cancle.setVisibility(View.GONE);
                tv_sign_des.setText((getResources().getString(R.string.sign_isokmode)));
                top_tips.setVisibility(View.GONE);
            }

        }
        tv_comtitle.setText(userModel.getNick());
        tv_meilino.setText(getResources().getString(R.string.sign_uid, userModel.getUid()));

        iv_vip.setImageResource(LevelHelper.getVIPIcon(userModel.getVip()));
        tv_user_level.setText(String.valueOf(userModel.getUserLevel()));
        tv_live_level.setText(String.valueOf(userModel.getLiveLevel()));
        tv_user_level.setBackgroundResource(LevelHelper.getUserLevelResId(userModel.getUserLevel()));
        tv_live_level.setBackgroundResource(LevelHelper.getLiveLevelResId(userModel.getLiveLevel()));
        GlideUtil.loadCircleImage(iv_comhead, userModel.getImgHead(), R.mipmap.pnl_00_head108);
    }

    @Override
    public void comeBack() {
        Intent intent = new Intent();
        intent.putExtra(PAYTYPE, paytype);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    private TextView otherTips() {
        TextView other = new TextView(this);
        other.setTextColor(getResources().getColor(R.color.text_75));
        other.setGravity(Gravity.CENTER_HORIZONTAL);
        other.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.sign_tipssize));
        String othertips = getResources().getString(R.string.sign_other);
        SpannableString spanstring = new SpannableString(othertips);
        int start = othertips.indexOf(",") + 1;
        spanstring.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                AboutIMayActivity.start(UserSignActivity.this);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(Color.parseColor("#507daf"));
                ds.setUnderlineText(false);
                ds.clearShadowLayer();
            }
        }, start, othertips.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        other.setText(spanstring);
        other.setMovementMethod(LinkMovementMethod.getInstance());
        return other;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.tv_signments == id) {
            WebViewActivity.startActivity(UserSignActivity.this, UrlHelper.SIGN_LICENSE);
        } else if (R.id.sign_cancle == id) {
            DialogFragmentHelper.showTipsDialog(getSupportFragmentManager(), getResources().getString(R.string.sign_cancletips), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        } else if (R.id.sign_ok == id) {
            if (sign_chekc.isChecked()) {
                DialogFragmentHelper.showLoadingDialog(getSupportFragmentManager(), getResources().getString(R.string.str_loading));
                ProtoRequestHelper.task(ProtoHttpFactory.getconfirmSign()).setTag(this.hashCode()).request(new ProtoCallBack() {
                    @Override
                    public void onRequestSuccess(String command, String data) {
                        Result<String> result = JSON.parseObject(data, new TypeReference<Result<String>>() {
                        }.getType());
                        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                        if (result.result == CodeSuccess && result.data != null) {
                            EventHelper.postSignChange();
                            DialogFragmentHelper.showTipsDialog(getSupportFragmentManager(), getResources().getString(R.string.sign_oktips), new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    finish();
                                }
                            });
                        } else {
                            ErrorResult.toastError(UserSignActivity.this, result.result);
                        }

                    }

                    @Override
                    public void onRequestError(String command, int code, String message) {
                        DialogFragmentHelper.closeLoadingDialog(getSupportFragmentManager());
                        ErrorResult.toastError(UserSignActivity.this, code);
                    }
                });
            } else {
                ToastUtil.show(UserSignActivity.this, getResources().getString(R.string.check_sign_agreementtitle));
            }
        } else if (id == R.id.sign_user_) {
            Long integer = (Long) v.getTag();
            ProfileActivity.start(UserSignActivity.this, integer);
        }
    }


    class NameView extends LinearLayout {
        private Paint paint;
        private Path path;
        TextView texttitle;

        public NameView(Context context) {
            super(context);
            init(context);
        }

        @Override
        protected void dispatchDraw(Canvas canvas) {
            super.dispatchDraw(canvas);
            if (path == null) {
                path = new Path();
                paint = new Paint();
                paint.setStyle(Paint.Style.STROKE);
                paint.setAntiAlias(true);
                paint.setStrokeWidth(4);
                paint.setColor(getResources().getColor(R.color.line_ec));
            }
            path.reset();
            path.moveTo(0, canvas.getHeight());
            path.lineTo(canvas.getWidth(), canvas.getHeight());
            canvas.drawPath(path, paint);
        }

        private void init(Context context) {
            setOrientation(HORIZONTAL);
            setBackgroundColor(getResources().getColor(R.color.bg_window));
            texttitle = new TextView(context);
            texttitle.setTextColor(getResources().getColor(R.color.text_75));
            LayoutParams titleparams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            titleparams.leftMargin = (int) getResources().getDimension(R.dimen.profitreallyname_top);
            titleparams.rightMargin = (int) getResources().getDimension(R.dimen.profitreallyname_top);
            titleparams.gravity = Gravity.CENTER_VERTICAL;
            addView(texttitle, titleparams);

        }

        public void setTextString(CharSequence text) {
            texttitle.setText(text);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec((int) getResources().getDimension(R.dimen.sign_title_height), MeasureSpec.EXACTLY));
        }
    }
}
